<?php


namespace app\api\controller;


use app\admin\validate\IDMustBePositiveInt;
use app\api\validate\OrderValidate;
use app\service\model\AttributeModel;
use app\service\model\CartModel;
use app\service\model\GoodsActivityModel;
use app\service\model\GoodsModel;
use app\service\model\GoodsSkuModel;
use app\service\model\MemberCouponModel;
use app\service\model\OrderModel;
use app\service\model\VoucherModel;
use app\service\Y;
use think\Exception;
use think\facade\Db;

class Order extends AuthApi
{

    /**
     * 订单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function order_list(): \think\response\Json
    {
        $where[] = ['member_id', '=', $this->member->id];
        $status = input('param.status', 0);
        if ($status > 0) {
            $where[] = ['status', '=', $status];
        }
        $data = OrderModel::with('order_goods.goods.images')->where($where)->order('id', 'desc')->paginate()->toArray()['data'];
        return Y::success($data, '订单列表');
    }

    /**
     * 订单详情
     * @param IDMustBePositiveInt $IDMustBePositiveInt
     * @return \think\response\Json
     * @throws \app\service\exception\ParameterException
     * @throws \think\db\exception\DbException
     */
    public function order_info(IDMustBePositiveInt $IDMustBePositiveInt): \think\response\Json
    {
        $IDMustBePositiveInt->goCheck();
        $id = input('param.id', 0);
        $data = OrderModel::where('id', '=', $id)->where('member_id', '=', $this->member->id)->find();
        return Y::success($data, '订单列表');
    }

    /**
     * 创建订单
     * @param OrderValidate $orderValidate
     * @return \think\response\Json
     * @throws \app\service\exception\ParameterException
     * @throws \think\Exception
     */
    public function create_order(OrderValidate $orderValidate): \think\response\Json
    {
        $orderValidate->goCheck();
        $param = $orderValidate->getDataByRule();

        $member_id = $this->member->id;
        $address_id = $param['address_id'];
        $appointment_time = $param['appointment_time'];

        $no_pay_order = OrderModel::field('id')->where('member_id', '=', $member_id)
            ->where('status', '=', 1)->find();
        if ($no_pay_order) {
            return Y::error('您有一笔未支付订单，请先支付或取消');
        }

        if ($param['type'] == 1) {
            // 直接购买
            $goods_id = input('param.goods_id', 0);
            $sku_id = input('param.sku_id', 0);
            $order = \app\service\business\Order::create_order_by_goods($goods_id, $sku_id, $address_id, $member_id, $appointment_time);
        } else {
            // 购物车下单
            $cart_ids = input('param.cart_ids/s', '');
            $order = \app\service\business\Order::create_order_by_cart($cart_ids, $address_id, $member_id, $appointment_time);

            // 下单成功，删除购物车
            CartModel::where('id', 'in', $cart_ids)->where('member_id', '=', $member_id)->delete();
        }
        return Y::success(['order_id' => $order->id], '下单成功');
    }

    /**
     * 获取创建订单的商品列表信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function goods_list(): \think\response\Json
    {
        $type = input('param.type');
        $id = input('param.id', 0);
        $cart_ids = input('param.cart_ids', '');
        if ($type == 1) {
            $sid = input('param.sid', 0);
            $data[] = $this->getGoods($id, $sid);
        } else {
            $cart_list = CartModel::where('id', 'in', $cart_ids)
                ->where('member_id', '=', $this->member->id)
                ->select();
            foreach ($cart_list as $c) {
                $goods = $this->getGoods($c->goods_id, $c->sku_id);
                $goods['num'] = $c->num;
                $data[] = $goods;
            }
        }
        return Y::success($data, '商品列表');
    }

    /**
     * 获取商品信息
     * @param $goods_id
     * @param $sku_id
     * @return array|\think\Model|null
     * @throws \app\service\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGoods($goods_id, $sku_id)
    {
        $goods = GoodsModel::where('id', '=', $goods_id)->find();
        $goods['image'] = $goods->images[0]->min_image ?? '';
        $goods['num'] = 1;
        if ($sku_id) {
            $sku = GoodsSkuModel::where('id', '=', $sku_id)->find();
            $goods['attribute'] = implode(' ', AttributeModel::where('id', 'in', $sku->attrs)->column('name'));
            $goods['price'] = $sku->price;
            $goods['image'] = $sku->min_image;
        }
        $activity = GoodsActivityModel::getActivity($goods_id);
        if ($activity) {
            $goods['activity_info'] = '原价：' . $goods['price'] . '元，' . $activity->name . '-' . $activity->discount . '折';
            $goods['price'] = $goods['price'] * ($activity->discount / 10);
        }
        return $goods;
    }

    /**
     * 取消订单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancel_order(): \think\response\Json
    {
        $order_id = input('param.order_id', 0);
        $order = OrderModel::where('id', '=', $order_id)
            ->where('member_id', '=', $this->member->id)
            ->find();
        if (!$order) {
            return Y::error('订单不存在');
        }
        if ($order->status != 1) {
            return Y::error('订单状态不可取消');
        }

        Db::startTrans();
        try {
            $order->save(['status' => 9]); //订单取消
            // 退还  优惠券、抵扣券、
            if ($order->voucher_id > 0) {
                VoucherModel::where('id', '=', $order->voucher_id)
                    ->where('member_id', '=', $order->member_id)->update([
                        'status' => 1
                    ]);
            }
            if ($order->member_coupon_id) {
                MemberCouponModel::where('id', '=', $order->member_coupon_id)
                    ->where('member_id', '=', $order->member_id)->update([
                        'status' => 1
                    ]);
            }

            Db::commit();
            return Y::success([], '取消成功');
        } catch (Exception $e) {
            Db::rollback();
            return Y::error('取消失败', [$e->getMessage(), $e->getFile(), $e->getLine()]);
        }
    }

    /**
     * 完成订单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function finish_order(): \think\response\Json
    {
        $order_id = input('param.order_id', 0);
        $order = OrderModel::where('id', '=', $order_id)
            ->where('member_id', '=', $this->member->id)
            ->find();
        if (!$order) {
            return Y::error('订单不存在');
        }
        if ($order->status != 2) {
            return Y::error('订单状态不可完成');
        }

        Db::startTrans();
        try {
            $order->save(['status' => 8]); //订单完成
            Db::commit();
            return Y::success([], '取消成功');
        } catch (Exception $e) {
            Db::rollback();
            return Y::error('取消失败', [$e->getMessage(), $e->getFile(), $e->getLine()]);
        }
    }
}